import store from '@/store'
/**
 * 存储localStorage
 */
export const setStore = (name, content) => {
  if (!name) return
  if (typeof content !== 'string') {
    content = JSON.stringify(content)
  }
  window.localStorage.setItem(name, content)
}

/**
 * 获取localStorage
 */
export const getStore = name => {
  if (!name) return
  var value = window.localStorage.getItem(name)
  if (value !== null) {
    try {
      value = JSON.parse(value)
    } catch (e) {
      // value = value
    }
  }
  return value
}

/**
 * 删除localStorage
 */
export const removeStore = name => {
  if (!name) return
  window.localStorage.removeItem(name)
}

/**
 * 让整数自动保留2位小数
 */
// export const returnFloat = value => {
//     var value=Math.round(parseFloat(value)*100)/100;
//     var xsd=value.toString().split(".");
//     if(xsd.length==1){
//         value=value.toString()+".00";
//         return value;
//     }
//     if(xsd.length>1){
//         if(xsd[1].length<2){
//             value=value.toString()+"0";
//         }
//         return value;
//     }
// }
/**
 * @param {date} 标准时间格式:Fri Nov 17 2017 09:26:23 GMT+0800 (中国标准时间)
 * @param {type} 类型
 *   type == 1 ---> "yyyy-mm-dd hh:MM:ss.fff"
 *   type == 2 ---> "yyyymmddhhMMss"
 *   type == '' ---> "yyyy-mm-dd hh:MM:ss"
 */
export const formatDate = (date, type) => {
  var year = date.getFullYear() // 年
  var month =
    date.getMonth() + 1 < 10
      ? '0' + (date.getMonth() + 1)
      : date.getMonth() + 1 // 月
  var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate() // 日
  var hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours() // 时
  var minutes =
    date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes() // 分
  var seconds =
    date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds() // 秒
  var milliseconds =
    date.getMilliseconds() < 10
      ? '0' + date.getMilliseconds()
      : date.getMilliseconds() // 毫秒
  if (type === 1) {
    return (
      year +
      '-' +
      month +
      '-' +
      day +
      ' ' +
      hour +
      ':' +
      minutes +
      ':' +
      seconds +
      '.' +
      milliseconds
    )
  } else if (type === 2) {
    return (
      year + '' + month + '' + day + '' + hour + '' + minutes + '' + seconds
    )
  } else if (type === 3) {
    return year + '-' + month + '-' + day
  } else {
    return (
      year +
      '-' +
      month +
      '-' +
      day +
      ' ' +
      hour +
      ':' +
      minutes +
      ':' +
      seconds
    )
  }
}
/**
 * 时间转换：20150101010101 --> '2015-01-01 01:01:01'
 */
export const parseToDate = timeValue => {
  var result = ''
  var year = timeValue.substr(0, 4)
  var month = timeValue.substr(4, 2)
  var date = timeValue.substr(6, 2)
  var hour = timeValue.substr(8, 2)
  var minute = timeValue.substr(10, 2)
  var second = timeValue.substr(12, 2)
  result =
    year + '-' + month + '-' + date + ' ' + hour + ':' + minute + ':' + second
  return result
}
/**
 * 判断空值
 */
export const isEmpty = keys => {
  if (typeof keys === 'string') {
    keys = keys.replace(/\"|&nbsp;|\\/g, '').replace(/(^\s*)|(\s*$)/g, '')
    if (keys === '' || keys == null || keys === 'null' || keys === 'undefined') {
      return true
    } else {
      return false
    }
  } else if (typeof keys === 'undefined') {
    // 未定义
    return true
  } else if (typeof keys === 'number') {
    return false
  } else if (typeof keys === 'boolean') {
    return false
  } else if (typeof keys === 'object') {
    if (JSON.stringify(keys) === '{}') {
      return true
    } else if (keys == null) {
      // null
      return true
    } else {
      return false
    }
  }

  if (keys instanceof Array && keys.length === 0) {
    // 数组
    return true
  }
}

/**
 * 返回两位的小数的字符串
 */
export const toFixedNum = num => {
  const tonum = Number(num).toFixed(2)
  return tonum
}

export const showMessage = () => {
  this.$message({
    showClose: true,
    message: '对不起，您暂无此操作权限~',
    type: 'success'
  })
}

/**
 * 读取base64
 */
export const readFile = file => {
  console.log(file)
  // var file = this.files[0];
  // 判断是否是图片类型
  if (!/image\/\w+/.test(file.raw.type)) {
    alert('只能选择图片')
    return false
  }
  var reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = function(e) {
    var filedata = {
      filename: file.name,
      filebase64: e.target.result
    }
    alert(e.target.result)
  }
}
/**
 * 动态插入css
 */
export const loadStyle = url => {
  const link = document.createElement('link')
  link.type = 'text/css'
  link.rel = 'stylesheet'
  link.href = url
  const head = document.getElementsByTagName('head')[0]
  head.appendChild(link)
}
/**
 * 设置浏览器头部标题
 */
export const setTitle = title => {
  title = title ? `${title}` : '沙特'
  window.document.title = title
}

export const param2Obj = url => {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"') +
      '"}'
  )
}

// 是否为正整数
export const isInteger = s => {
  var re = /^[0-9]+$/
  return re.test(s)
}

export const setContentHeight = (that, ele, height) => {
  that.$nextTick(() => {
    ele.style.height = document.body.clientHeight - height + 'px'
  })
}

// 导出文件 只适用于get请求
export const exportFile = (fileName, responseURL) => {
  const tempLink = document.createElement('a')
  tempLink.style.display = 'none'
  tempLink.href = responseURL
  tempLink.setAttribute('download', fileName)
  document.body.appendChild(tempLink)
  tempLink.click()
  document.body.removeChild(tempLink)
}

/**
 * 数据筛选赋值
 */

export const assignment = (checkedCities, columnsListcc) => {
  const columnsList = []
  for (const i in columnsListcc) {
    if (
      columnsListcc[i].prop !== 'ids' &&
      columnsListcc[i].prop !== 'opeText'
    ) {
      for (const k in checkedCities) {
        if (columnsListcc[i].label === checkedCities[k]) {
          columnsList.push(columnsListcc[i])
        }
      }
    }
  }
  columnsList.unshift({
    prop: 'ids',
    label: '序号',
    align: 'center'
  })
  const opeTextCol = columnsListcc.find(it => it.prop === 'opeText')
  if (opeTextCol) {
    columnsList.push(opeTextCol)
  }
  return columnsList
}

// /**
//  * 构造树型结构数据
//  * @param {*} data 数据源
//  * @param {*} id id字段 默认 'id'
//  * @param {*} parentId 父节点字段 默认 'parentId'
//  * @param {*} children 孩子节点字段 默认 'children'
//  * @param {*} rootId 根Id 默认 0
//  */

export const handleTree = (data, id, parentId, children, rootId) => {
  id = id || 'id'
  parentId = parentId || 'parentId'
  children = children || 'children'
  rootId = rootId || 0
  // 对源数据深度克隆
  const cloneData = JSON.parse(JSON.stringify(data))
  // 循环所有项
  const treeData = cloneData.filter(father => {
    const branchArr = cloneData.filter(child => {
      // 返回每一项的子级数组
      return father[id] === child[parentId]
    })
    branchArr.length > 0 ? (father.children = branchArr) : ''
    // 返回第一层
    return father[parentId] === rootId
  })
  const newTreeData = setTree(treeData)
  return treeData !== '' ? newTreeData : data
}

function setTree(treeData) {
  for (let i = 0; i < treeData.length; i++) {
    if (treeData[i].children && treeData[i].children.length === 0) {
      delete treeData[i].children
    } else {
      setTree(treeData[i].children)
    }
  }
  return treeData
}

/**
 * @param {string} path
 * @returns {Boolean}
 */
export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path)
}

/**
 * 权限匹配
 * @param {*} idsArray  权限标识数组
 */
export function hasPermi(idsArray = []) {
  const all_permission = '*:*:*'
  const permissions = store.getters && store.getters.permissions
  const permissionFlag = idsArray
  return permissions.some(permission => {
    return all_permission === permission || permissionFlag.includes(permission)
  })
}
/**
 * 通过key值拿到对应的Name
 * @param {*} idsArray  权限标识数组
 */
export function matchValue(array = [], keyVal, key = 'id', val = 'value') {
  const matchObj = array.find(item => item[key] === keyVal)
  return matchObj[val]
}

/**
 * 设置表格高度
 * @param {*} _this vue实例
 * @param {*} cusHeight 自定义高度
 */
export function setTableHeight(_this, cusHeight = 0) {
  const headerHeight = document.querySelector('.navbar').offsetHeight // 头部高度
  const filterHeight = _this.$refs.conditionForm
    ? _this.$refs.conditionForm.$el.offsetHeight + 10
    : 0 // 条件筛选项高度
  const buttonRowsHeight = _this.$refs.buttonRows
    ? _this.$refs.buttonRows.offsetHeight
      ? _this.$refs.buttonRows.offsetHeight + 10
      : _this.$refs.buttonRows.$el.offsetHeight + 10
    : 38 // 按钮的高度
  const comHeight =
    headerHeight + filterHeight + cusHeight + buttonRowsHeight + 78
  return `calc(100vh - (${comHeight}px))`
}

// 2个数字相减
export function argSubtraction(arg1 = 0, arg2 = 0) {
  const result = [Number(arg1) * 1000 - Number(arg2) * 1000] / 1000
  return result
}

// 2个数字相加
export function argAdd(arg1 = 0, arg2 = 0) {
  const result = [Number(arg1) * 1000 + Number(arg2) * 1000] / 1000
  return result
}
